// import packages
import Vue from 'vue';
import store from '@/store/index';
import VueRouter from 'vue-router';
import { getUserToken } from '@/common/utils';

// import components
const Error = () => import('@/views/Error/Error.vue');
const Login = () => import('@/views/Login/Login.vue');
const Home = () => import('@/views/Home/Home.vue');
const Contacts = () => import('@/views/Contacts/Contacts.vue');
const Visit = () => import('@/views/Visit/Visit.vue');
const Statistics = () => import('@/views/Statistics/Statistics.vue');

// Setup Vue
Vue.use(VueRouter);

// Setup Router
const router = new VueRouter({
	routes: [
		{
			path: '/',
			component: Home,
			meta: { breadcrumb: '首页' },
			redirect: '/contacts',
			children: [
				{
					path: '/contacts',
					component: Contacts,
					meta: { breadcrumb: '通讯录管理' },
				},
				{
					path: '/visit',
					component: Visit,
					meta: { breadcrumb: '访客申请记录' },
				},
				{
					path: '/statistics',
					component: Statistics,
					meta: { breadcrumb: '数据统计' },
				},
			],
		},
		{
			path: '/login',
			component: Login,
		},
		{
			path: '*',
			component: Error,
		},
	],
});

// Config router guard
router.beforeEach((to, from, next) => {
	const token = store.state.user.token || getUserToken(); 

	if (to.path === '/login') {
		next();
	} else {
		if (!token) {
			next('/login');
		} else {
			next();
		}
	}
});

export default router;
